package com.example.astronautcontact0123456789hwh1104;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
    ContactDAL contactDAL;
    private ImageView ivMainMore;
    private RecyclerView rvMainContact;
    private FloatingActionButton fabtnMainAdd;
    List<AstronautContact> contactList=new ArrayList<>();
    private ContactRVAdapter contactRVAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        contactDAL = new ContactDAL(this);
//        contactDAL.openDatabase();
//        contactDAL.closeDatabase();
        initView();
        fabtnMainAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View view=getLayoutInflater().inflate(R.layout.dialog_contact,null);
                new AlertDialog.Builder(MainActivity.this)
                        .setView(view)
                        .setTitle("新建联系人")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
//                                读取数据，然后插入数据库//
                                String name = ((EditText)view.findViewById(R.id.edtTxtDialogName)).getText().toString().trim();
                                String phone = ((EditText)view.findViewById(R.id.edtTxtDialogPhone)).getText().toString().trim();
                                String email = ((EditText)view.findViewById(R.id.edtTxtDialogEmail)).getText().toString().trim();
                                String organization = ((EditText)view.findViewById(R.id.edtTxtDialogOrganization)).getText().toString().trim();
                                String notes = ((EditText)view.findViewById(R.id.edtTxtDialogNotes)).getText().toString().trim();
                                AstronautContact contact = new AstronautContact(name, phone, email, organization, notes);
                                if(contactDAL.insertContact(contact)!=-1){
                                    Toast.makeText(MainActivity.this, "添加成功", Toast.LENGTH_SHORT).show();

                                    contactList = contactDAL.queryAll();
                                    contactRVAdapter.setContactList(contactList);
                                    rvMainContact.getAdapter().notifyDataSetChanged();
                                }else {
                                    Toast.makeText(MainActivity.this, "添加失败", Toast.LENGTH_SHORT).show();
                                }

                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();//关闭对话框
                            }
                        })
                        .create()
                        .show();
            }
        });
        ivMainMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupMenu popupMenu = new PopupMenu(MainActivity.this, v);
                popupMenu.getMenuInflater().inflate(R.menu.main_popup_menu, popupMenu.getMenu());
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem menuItem) {
                        int itemId = menuItem.getItemId();
                        if(itemId==R.id.itemMenuBackup){//备份，拿数据，访问文件，写入文件
                            contactList = contactDAL.queryAll();//从数据库中查询所有数据
                            try{
                                FileOutputStream fos=openFileOutput("contactBackup.data",MODE_PRIVATE);
                                ObjectOutputStream oos=new ObjectOutputStream(fos);
                                oos.writeObject(contactList);
                                oos.flush();
                                oos.close();
                                fos.close();
                                Toast.makeText(MainActivity.this,"备份成功",Toast.LENGTH_SHORT).show();
                            }catch (Exception e){
                                e.getStackTrace();
                                Toast.makeText(MainActivity.this,"备份失败",Toast.LENGTH_SHORT).show();
                            }

                            return true;
                        }else if(itemId==R.id.itemMenuLoad){//还原，访问文件，读数据，插入数据库
                            try{
                                FileInputStream fis=openFileInput("contactBackup.data");
                                ObjectInputStream ois=new ObjectInputStream(fis);
                                List<AstronautContact> contactList=(List<AstronautContact>)ois.readObject();
                                ois.close();
                                fis.close();
                                contactDAL.deleteAll();
                                contactDAL.insertList(contactList);
                                contactRVAdapter.setContactList(contactList);
                                rvMainContact.getAdapter().notifyDataSetChanged();
                                Toast.makeText(MainActivity.this,"还原成功",Toast.LENGTH_SHORT).show();
                            }catch (Exception e){
                                e.getStackTrace();
                                Toast.makeText(MainActivity.this,"还原失败",Toast.LENGTH_SHORT).show();
                            }

                            return true;
                        }else {
                            return false;
                        }
                    }
                });
                popupMenu.show();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        contactList = contactDAL.queryAll();
        contactRVAdapter = new ContactRVAdapter();
        contactRVAdapter.setContactList(contactList);
        rvMainContact.setLayoutManager(new LinearLayoutManager(this));
        rvMainContact.setAdapter(contactRVAdapter);
    }

    private void initView() {
        ivMainMore = (ImageView) findViewById(R.id.ivMainMore);
        rvMainContact = (RecyclerView) findViewById(R.id.rvMainContact);
        fabtnMainAdd = (FloatingActionButton) findViewById(R.id.fabtnMainAdd);
    }
}